
#include "UploadHandler.h"

#include <QDataStream>

#include <Manager/FileManager.h>
#include <Manager/SignatureManager.h>
#include <Cpu.h>

using namespace std;

namespace TCServer
{
    namespace RPHandler
    {
        UploadHandler::UploadHandler()
        {
            assert(_instance == nullptr);
            // #TODO: initialize class

            setOn("upload/prepare", this, &UploadHandler::prepare);

            _instance = this;
        }

        UploadHandler::~UploadHandler()
        {
            _instance = nullptr;
        }

        void UploadHandler::prepare(QDataStream &stream, QVariantMap args)
		{
			auto res = Manager::SignatureManager::instance()->check(args.value("signature").toByteArray());

			if (get<bool>(res))
			{
				auto permissions = get<QSet<Type::Permission>>(res);
// 				if (permissions.contains(Type::Permission::User))
				{
					auto userId = get<quint64>(res);
					auto ip = args.value("extra.ip").toString();
                    auto suffix = args.value("suffix").toString();
					auto datetimestr = args.value("datetime").toString();
					auto md5inbase64 = args.value("md5inbase64").toString();
					auto prepareResult = Manager::FileManager::instance()->prepareUpload(ip, userId, md5inbase64, suffix);
					if (prepareResult.success)
					{
						stream << true <<
							std::move(prepareResult.datetimestr) <<
							std::move(prepareResult.path) <<
							std::move(prepareResult.signature) <<
							std::move(prepareResult.contentType) <<
							std::move(prepareResult.ossHeaders);
						return;
					}
				}
			}
			stream << false;
        }

        UploadHandler* UploadHandler::instance()
        {
            if (_instance == nullptr)
                _instance = new UploadHandler;
            return _instance;
        }

        UploadHandler* UploadHandler::_instance = nullptr;
    }

}